import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { smartPreload } from '@/utils/routePreload'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      component: () => import('@/layouts/AppLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          redirect: '/dashboard'
        },
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '仪表板' }
        },
        {
          path: 'monitor',
          name: 'Monitor',
          component: () => import('@/views/monitor/MonitorLayout.vue'),
          meta: { title: '数据监控' },
          children: [
            {
              path: '',
              redirect: '/monitor/overview'
            },
            {
              path: 'overview',
              name: 'MonitorOverview',
              component: () => import('@/views/monitor/MonitorOverview.vue'),
              meta: { title: '数据概览' }
            },
            {
              path: 'tables',
              name: 'TableList',
              component: () => import('@/views/monitor/TableList.vue'),
              meta: { title: '数据列表' }
            },
            {
              path: 'layer/:layerName',
              name: 'LayerMonitor',
              component: () => import('@/views/monitor/LayerMonitor.vue'),
              meta: { title: '层监控详情' }
            }
          ]
        },
        {
          path: 'flink',
          name: 'Flink',
          component: () => import('@/views/flink/FlinkLayout.vue'),
          meta: { title: 'Flink作业' },
          children: [
            {
              path: '',
              redirect: '/flink/jobs'
            },
            {
              path: 'jobs',
              name: 'FlinkJobs',
              component: () => import('@/views/flink/FlinkJobs.vue'),
              meta: { title: '作业管理' }
            },
            {
              path: 'mappings',
              name: 'FlinkMappings',
              component: () => import('@/views/flink/FlinkMappings.vue'),
              meta: { title: '作业映射' }
            }
          ]
        },
        {
          path: 'task-monitor',
          name: 'TaskMonitor',
          component: () => import('@/views/TaskMonitor.vue'),
          meta: { title: '异步任务监控' }
        },
        {
          path: 'alert',
          name: 'Alert',
          component: () => import('@/views/alert/AlertLayout.vue'),
          meta: { title: '告警管理' },
          children: [
            {
              path: '',
              redirect: '/alert/rules'
            },
            {
              path: 'rules',
              name: 'AlertRules',
              component: () => import('@/views/alert/AlertRules.vue'),
              meta: { title: '告警规则' }
            },
            {
              path: 'history',
              name: 'AlertHistory',
              component: () => import('@/views/alert/AlertHistory.vue'),
              meta: { title: '告警历史' }
            }
          ]
        },
        {
          path: 'report',
          name: 'Report',
          component: () => import('@/views/report/ReportLayout.vue'),
          meta: { title: '报表中心' },
          children: [
            {
              path: '',
              redirect: '/report/list'
            },
            {
              path: 'list',
              name: 'ReportList',
              component: () => import('@/views/report/ReportList.vue'),
              meta: { title: '报表定义' }
            },
            {
              path: 'executions',
              name: 'ReportExecutions',
              component: () => import('@/views/report/ReportExecutions.vue'),
              meta: { title: '执行历史' }
            },

          ]
        },
        {
          path: 'system',
          name: 'System',
          component: () => import('@/views/system/SystemLayout.vue'),
          meta: { title: '系统设置' },
          children: [
            {
              path: '',
              redirect: '/system/configs'
            },
            {
              path: 'configs',
              name: 'SystemConfigs',
              component: () => import('@/views/system/SystemConfigs.vue'),
              meta: { title: '系统配置' }
            },
            {
              path: 'database',
              name: 'DatabaseConfigs',
              component: () => import('@/views/system/DatabaseConfigs.vue'),
              meta: { title: '数据库配置' }
            },
            {
              path: 'wechat-bots',
              name: 'WechatBots',
              component: () => import('@/views/system/WechatBots.vue'),
              meta: { title: '微信机器人' }
            }
          ]
        },
        {
          path: 'profile',
          name: 'Profile',
          component: () => import('@/views/Profile.vue'),
          meta: { title: '个人资料' }
        },
        {
          path: 'settings',
          name: 'Settings',
          component: () => import('@/views/Settings.vue'),
          meta: { title: '设置' }
        },

      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue'),
      meta: { requiresAuth: false }
    }
  ]
})

// 路由守卫 - 优化版本
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    // 尝试初始化认证状态
    try {
      await authStore.initAuth()
      if (authStore.isAuthenticated) {
        next()
        return
      }
    } catch (error) {
      console.error('Auth init failed:', error)
    }
    
    // 重定向到登录页
    next('/login')
    return
  }
  
  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && authStore.isAuthenticated) {
    next('/')
    return
  }
  
  // 智能预加载 - 优化版本，减少不必要的预加载
  if (to.name && typeof to.name === 'string' && from.name !== to.name) {
    // 只在路由真正变化时才预加载
    requestIdleCallback(() => {
      smartPreload(to.name as string)
    }, { timeout: 1000 })
  }
  
  next()
})

export default router 